package rexsee.core.browser;

import java.util.HashMap;

import rexsee.core.browser.clazz.JavascriptInterface;
import rexsee.core.browser.clazz.PageReadyListeners.PageReadyListener;
import android.content.Context;

public class RexseeInception implements JavascriptInterface {

	public static final String INTERFACE_NAME = "Inception";
	@Override
	public String getInterfaceName() {
		return mBrowser.application.resources.prefix + INTERFACE_NAME;
	}
	@Override
	public JavascriptInterface getInheritInterface(Browser childBrowser) {
		return new RexseeInception(childBrowser);
	}
	@Override
	public JavascriptInterface getNewInterface(Browser childBrowser) {
		return new RexseeInception(childBrowser);
	}

	private final HashMap<String, String> mMap;

	private final Browser mBrowser;

	public RexseeInception(Browser browser) {
		mBrowser = browser;
		mMap = new HashMap<String, String>();
		browser.pageReadyListeners.add(new PageReadyListener() {
			@Override
			public void run(Context context, Browser browser, String url) {
				try {
					if (mMap.isEmpty()) return;
					Object[] keys = mMap.keySet().toArray();
					for (int i = 0; i < keys.length; i++) {
						browser.loadUrl("javascript:" + mMap.get(keys[i].toString()));
					}
				} catch (Exception e) {
					browser.exception(getInterfaceName(), e);
				}
			}
		});
	}

	//JavaScript Interface
	public boolean add(String id, String code) {
		if (mMap.containsKey(id)) return false;
		else {
			mMap.put(id, code);
			return true;
		}
	}
	public String get(String id) {
		return mMap.get(id);
	}
	public void remove(String id) {
		mMap.remove(id);
	}
	public void remove() {
		Object[] keys = mMap.keySet().toArray();
		for (int i = 0; i < keys.length; i++) {
			mMap.remove(keys[i].toString());
		}
		mMap.clear();
	}
	public int size() {
		return mMap.size();
	}
	public boolean contains(String id) {
		return mMap.containsKey(id);
	}
	public String getKeys() {
		Object[] keys = mMap.keySet().toArray();
		String rtn = "";
		for (int i = 0; i < keys.length; i++) {
			rtn += (i == 0) ? "\"" + keys[i].toString() + "\"" : ",\"" + keys[i].toString() + "\"";
		}
		return "[" + rtn + "]";
	}

}
